package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理类的接口")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    private String PREFIX = "listCache:";

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO) {
        log.info("我来新增菜品");
        dishService.addDish(dishDTO);
        redisTemplate.delete(PREFIX + "category_Id=" + dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("我是可以通过DTO来接受路径参数的");
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping
    @ApiOperation("删除菜品数据")
    public Result deleteDish(@RequestParam(value = "ids") List<Long> dishIds) {
        log.info("我来批量或一个删除数据，传入的参数：{}",dishIds);
        dishService.deleteDish(dishIds);

        //删除redis中全部的列表数据!
        cleanCache(PREFIX + "category_Id=*");
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据Id查菜品")
    public Result<DishVO> queryDish(@PathVariable Long id) {
        DishVO dish = dishService.getByIdWithFlavor(id);
        return Result.success(dish);
    }

    @PutMapping
    @ApiOperation("根据提交过来的数据更新菜品信息")
    public Result updateDish(@RequestBody DishVO dishVO) {
        dishService.updateWithFlavor(dishVO);

        cleanCache(PREFIX + "category_Id=*");

        return Result.success();
    }


    @PostMapping("/status/{status}")
    public Result changeDishStatus(@PathVariable Integer status ,@RequestParam(value = "id")Integer id) {
        log.info("切换菜品id={}的状态：",id);
        dishService.changeDishStatus(status,id);
        return Result.success();
    }

    private void cleanCache(String prefix) {
        //删除redis中全部的列表数据!
        Set keys = redisTemplate.keys(prefix);
        if (keys != null) {
            redisTemplate.delete(keys);
        }
    }
}
